<template>
  <view class="container">
   <uni-forms ref="form" :model="formData" :rules="rules">
		<!-- 文章分类 -->
		<uni-forms-item label="文章分类" name="title" required>
		<uni-data-select
		        v-model="value"
		        :localdata="range"
		        @change="change()"
		></uni-data-select>
		</uni-forms-item>
      <!-- 文章标题 -->
      <uni-forms-item label="文章标题" name="title" required>
        <uni-easyinput 
          type="text" 
          v-model="formData.title" 
          placeholder="请输入文章标题"
          trim="both"
        />
      </uni-forms-item>
      
      <!-- 文章描述 -->
      <uni-forms-item label="文章描述" name="description">
        <uni-easyinput 
          type="textarea" 
          v-model="formData.description" 
          placeholder="请输入文章描述"
          :maxlength="200"
          autoHeight
        />
      </uni-forms-item>
      
      <!-- 封面图片上传 -->
      <uni-forms-item label="封面图片">
        <view class="cover-uploader">
          <view v-if="formData.coverUrl" class="cover-preview">
            <image :src="formData.coverUrl" mode="aspectFill" class="cover-image"></image>
            <view class="cover-actions">
              <text class="action-btn" @click="previewCover">预览</text>
              <text class="action-btn" @click="removeCover">删除</text>
            </view>
          </view>
          <view v-else class="upload-btn" @click="chooseCover">
            <uni-icons type="plusempty" size="30" color="#999"></uni-icons>
            <text class="upload-text">添加封面</text>
          </view>
        </view>
        <text class="upload-tip">建议尺寸：750x420像素，大小不超过2MB</text>
      </uni-forms-item>
      
      <!-- 富文本编辑器 -->
      <view class="editor-container">
        <text class="editor-label">文章内容</text>
        <editor 
          id="editor" 
          class="editor" 
          placeholder="请输入文章内容" 
          @ready="onEditorReady"
          @input="onEditorInput"
          show-img-size
          show-img-toolbar
          show-img-resize
        ></editor>
      </view>
      
      <!-- 提交按钮 -->
      <button type="primary" @click="submitForm" class="submit-btn">发布文章</button>
    </uni-forms>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        title: '',
        description: '',
        coverUrl: '',
        content: '',
        coverFile: null, // 用于存储上传的文件对象
      },
	  value: 1,
	  range: [
	      { value: 0, text: "美食" },
	      { value: 1, text: "旅行" },
	      { value: 2, text: "科技" },
		  { value: 0, text: "游戏" },
		  { value: 1, text: "动漫" },
		  { value: 2, text: "体育" }
	  ],
      rules: {
        title: {
          rules: [
            { required: true, errorMessage: '请输入文章标题' },
            { minLength: 3, maxLength: 50, errorMessage: '标题长度在3-50个字符之间' }
          ]
        },
        description: {
          rules: [
            { maxLength: 200, errorMessage: '描述不能超过200个字符' }
          ]
        }
      },
      editorCtx: null
    }
  },
  methods: {
	  change(e) {
	          console.log("e:", e);
	        },
    // 编辑器初始化完成回调
    onEditorReady() {
      uni.createSelectorQuery().select('#editor').context((res) => {
        this.editorCtx = res.context
      }).exec()
    },
    
    // 编辑器内容变化回调
    onEditorInput(e) {
      this.formData.content = e.detail.html
    },
    
    // 选择封面图片
    chooseCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 检查图片大小
          uni.getFileInfo({
            filePath: tempFilePath,
            success: (fileRes) => {
              if (fileRes.size > 2 * 1024 * 1024) {
                uni.showToast({
                  title: '图片大小不能超过2MB',
                  icon: 'none'
                })
                return
              }
              
              // 显示图片
              this.formData.coverUrl = tempFilePath
              this.formData.coverFile = res.tempFiles[0]
              
              // 这里可以添加图片压缩逻辑
              // this.compressImage(tempFilePath)
            }
          })
        }
      })
    },
    
    // 压缩图片（可选）
    compressImage(filePath) {
      uni.compressImage({
        src: filePath,
        quality: 80,
        success: (res) => {
          this.formData.coverUrl = res.tempFilePath
          // 更新文件对象
          uni.getFileInfo({
            filePath: res.tempFilePath,
            success: (fileRes) => {
              this.formData.coverFile = {
                path: res.tempFilePath,
                size: fileRes.size,
                type: 'image'
              }
            }
          })
        }
      })
    },
    
    // 预览封面
    previewCover() {
      if (!this.formData.coverUrl) return
      
      uni.previewImage({
        urls: [this.formData.coverUrl],
        current: 0
      })
    },
    
    // 删除封面
    removeCover() {
      this.formData.coverUrl = ''
      this.formData.coverFile = null
    },
    
    // 上传封面到服务器
    async uploadCover() {
      if (!this.formData.coverFile) return ''
      
      try {
        uni.showLoading({
          title: '上传封面中...',
          mask: true
        })
        
        // 这里替换为你的实际上传逻辑
        // 示例使用uni.uploadFile
        const uploadRes = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: 'https://your-api-domain.com/upload',
            filePath: this.formData.coverUrl,
            name: 'file',
            formData: {
              'type': 'article_cover'
            },
            header: {
              'Authorization': 'Bearer ' + getApp().globalData.token
            },
            success: resolve,
            fail: reject
          })
        })
        
        const resData = JSON.parse(uploadRes.data)
        if (resData.code === 200) {
          return resData.data.url // 返回服务器上的图片URL
        } else {
          throw new Error(resData.message || '上传失败')
        }
      } catch (error) {
        console.error('封面上传失败:', error)
        uni.showToast({
          title: '封面上传失败: ' + error.message,
          icon: 'none'
        })
        throw error
      } finally {
        uni.hideLoading()
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        // 表单验证
        await this.$refs.form.validate()
        
        if (!this.formData.content) {
          uni.showToast({
            title: '请填写文章内容',
            icon: 'none'
          })
          return
        }
        
        uni.showLoading({
          title: '发布中...',
          mask: true
        })
        
        // 如果有封面图片，先上传封面
        let coverUrl = ''
        if (this.formData.coverUrl) {
          coverUrl = await this.uploadCover()
        }
        
        // 组装提交数据
        const submitData = {
          title: this.formData.title,
          description: this.formData.description,
          content: this.formData.content,
          cover_url: coverUrl
        }
        
        // 提交到服务器
        const res = await this.$http.post('/articles', submitData)
        
        uni.hideLoading()
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        
        // 发布成功后返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        uni.hideLoading()
        console.error('发布失败:', error)
        
        if (error.message !== '封面上传失败') {
          uni.showToast({
            title: '发布失败: ' + (error.message || '未知错误'),
            icon: 'none'
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.editor-container, .cover-uploader {
  margin-top: 30rpx;
  margin-bottom: 40rpx;
}

.editor-label, .upload-tip {
  display: block;
  margin-bottom: 15rpx;
  font-size: 28rpx;
  color: #666;
}

.upload-tip {
  color: #999;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.editor {
  width: 100%;
  min-height: 500rpx;
  border: 1px solid #e5e5e5;
  border-radius: 8rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.cover-uploader {
  border: 1px dashed #e5e5e5;
  border-radius: 8rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200rpx;
  color: #999;
}

.upload-text {
  margin-top: 10rpx;
  font-size: 26rpx;
}

.cover-preview {
  position: relative;
}

.cover-image {
  width: 100%;
  height: 300rpx;
  border-radius: 8rpx;
}

.cover-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 15rpx 0;
  border-bottom-left-radius: 8rpx;
  border-bottom-right-radius: 8rpx;
}

.action-btn {
  color: #fff;
  font-size: 26rpx;
  padding: 5rpx 20rpx;
}

.submit-btn {
  margin-top: 50rpx;
}
</style>